﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Forest.Cat.Web.Models;
using Forest.Cat.Domain.Services.Jobseekers;
using Forest.Cat.Domain.Services.Authentication;
using System.Web.Security;
using Forest.Cat.Web.Extensions;
using Forest.Cat.Web.Models.Jobseekers;
using Forest.Cat.Domain.Services.Catalog;
using Forest.Cat.Domain.Services.Applications;
using Forest.Cat.Web.Models.Catalog;
using Forest.Cat.Domain.Entities;
using Forest.Cat.Domain.Services.Compnaies;
using Forest.Cat.Domain.Configuration;
using Forest.Cat.Domain.Shared;
using Forest.Cat.Domain.Services;
using Forest.Cat.Domain;
using Forest.Cat.Domain.Shared.Security;
using System.Text;
using Forest.Core;

namespace Forest.Cat.Web.Controllers
{
    public class JobseekerController : BaseController
    {
        #region Fields
        private int size = 5;
        private readonly IJobseekerService _jobseekerService;
        private readonly IJobseekerRegistrationService _jobseekerRegistrationService;
        private readonly IAuthenticationService _authenticationService;
        private readonly IEncryptionService _encryptionService;
        private readonly IJobPositionService _jobPositionService;
        private readonly IWorkContext _workContext;
        private readonly HttpContextBase _httpContext;
        #endregion

        #region Constructures
        public JobseekerController(IJobseekerRegistrationService jobseekerRegistrationService,
            IJobseekerService jobseekerService,
            IAuthenticationService authenticationService,
            IEncryptionService encryptionService,
            IJobPositionService jobPositionService,
            IWorkContext workContext,
            HttpContextBase httpContext)
        {
            _jobseekerService = jobseekerService;
            _jobseekerRegistrationService = jobseekerRegistrationService;
            _authenticationService = authenticationService;
            _encryptionService = encryptionService;
            _jobPositionService = jobPositionService;
            _workContext = workContext;
            _httpContext = httpContext;
        }
        #endregion

        #region Methods
        #region Login/logout

        [ChildActionOnly]
        public ActionResult Login()
        {
            return PartialView(PrepareLoginModel(_workContext.CurrentUser));
        }

        [HttpPost]
        public ActionResult DoLogin(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (_jobseekerRegistrationService.ValidateUser(model.Email, model.Password))
                {
                    var jobseeker = _jobseekerService.GetUserByEmail(model.Email);
                    // Sign In New User
                    _authenticationService.SignIn(jobseeker, model.RememberMe);
                    if (!String.IsNullOrWhiteSpace(returnUrl))
                        return Redirect(returnUrl);
                    else
                        return RedirectToAction("index", "home");
                }
                else
                {
                    return RedirectToAction("LoginPage");
                }
            }
            return PartialView(model);
        }

        private LoginModel PrepareLoginModel(Jobseeker jobseeker)
        {
            LoginModel loginModel = null;
            if (jobseeker != null)
            {
                var companyLetterCount = _jobPositionService.GetReceivedMessageList(jobseeker.Id).Count();
                loginModel = new LoginModel()
                {
                    FullName = jobseeker.FullName,
                    CompanyLetterCount = companyLetterCount,
                };
            }
            return loginModel;
        }

        public ActionResult Logout()
        {
            _authenticationService.SignOut();
            return this.RedirectToAction("Index", "Home");
        }
        #endregion

        #region Register
        public ActionResult Register()
        {
            var model = new RegisterModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                if (_jobseekerService.GetUserByEmail(model.Email) != null)
                {
                    ModelState.AddModelError("EmailExist", "邮件地址已存在");
                }
                else
                {
                    var saltKey = _encryptionService.CreateSaltKey(5);
                    var md5Password = _encryptionService.CreatePasswordHash(model.Password, saltKey);
                    //插入求职者记录
                    var jobseeker = new Jobseeker()
                    {
                        DateCreated = DateTime.Now,
                        Email = model.Email,
                        Password = md5Password,
                        Id = Guid.NewGuid(),
                        PasswordFormat = (int)PasswordFormat.Hashed,
                        PasswordSalt = saltKey,
                        IDCard = "0",
                    };

                    //注册 
                    var registrationRequest = new JobseekerRegistrationRequest(jobseeker, model.Email, model.UserName, md5Password);
                    var registrationResult = _jobseekerRegistrationService.RegisterJobseeker(registrationRequest);

                    if (registrationResult.Success)
                    {
                        jobseeker.LastSignedIn = DateTime.Now;
                        // Save Last signed in date
                        _jobseekerService.UpdateUser(jobseeker);
                        _authenticationService.SignIn(jobseeker, true);
                        return RedirectToAction("Index", "Home");
                    }
                }
            }
            return View(model);
        }
        #endregion

        #region RetrievePassword
        public ActionResult RetrievePassword()
        {
            var model = new RetrievePasswordModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult RetrievePassword(RetrievePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                //获取人员信息
                var jobseeker = _jobseekerService.GetUserByEmail(model.Email) ?? _jobseekerService.GetUserByResumeEmail(model.Email);
                //如果在jobseeker和resume中都检索不到输入的邮件地址
                if (jobseeker == null)
                {
                    ModelState.AddModelError("emailUnExist", "邮件地址不存在，请重新输入");
                }
                else
                {
                    //取的随机密码
                    var charList = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
                    var random = new Random();
                    var passWordLength = 6;
                    var passWordList = new StringBuilder();
                    for (int i = 0; i < passWordLength; i++)
                    {
                        var index = random.Next(0, 61);
                        passWordList.Append(charList[index].ToString());
                    }
                    //更新密码
                    var saltKey = _encryptionService.CreateSaltKey(5);
                    var md5Password = _encryptionService.CreatePasswordHash(passWordList.ToString(), saltKey);
                    jobseeker.PasswordSalt = saltKey;
                    jobseeker.Password = md5Password;
                    _jobseekerService.UpdateUser(jobseeker);
                    //发送邮件
                    MailHelper.SendMail(model.Email, "新世纪人才网密码重置确认信",
                        String.Format("您好，您的用户名:{0};密码更新为{1}", jobseeker.Email, passWordList.ToString()));
                    ViewBag.Js = "<script>$(function(){alert('邮件发送成功');window.location = '" + Url.Action("index", "home") + "';}); </script>";
                }
            }
            return View(model);
        }

        #endregion

        #region PopupLogin
        public ActionResult PopupLogin()
        {
            return PartialView(new LoginModel());
        }

        [HttpPost]
        public ActionResult PopupLogin(LoginModel model, string returnUrl, String btnPopupLogin)
        {
            if (!String.IsNullOrWhiteSpace(btnPopupLogin) && btnPopupLogin.Equals("btnPopupLogin"))
            {
                if (ModelState.IsValid)
                {
                    if (_jobseekerRegistrationService.ValidateUser(model.Email, model.Password))
                    {
                        var jobseeker = _jobseekerService.GetUserByEmail(model.Email);
                        // Sign In New User
                        _authenticationService.SignIn(jobseeker, model.RememberMe);
                        Response.Write("<script>window.location = location.href ;</script>");
                    }
                    else
                    {
                        //Response.Write("<script>window.location = '" + Url.Action("LoginPage") + "';</script>");
                        ModelState.AddModelError("loginError", "用户名或密码错误");
                    }
                }
                return PartialView("PopupLogin", model);
            }
            else
            {
                return PartialView();
            }
        }
        #endregion

        #region LoginPage
        public ActionResult LoginPage()
        {
            var model = new LoginModel();
            if (Request.Cookies["Email"] != null)
            {
                model.Email = Request.Cookies["Email"].Value;
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult LoginPage(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                if (_jobseekerRegistrationService.ValidateUser(model.Email, model.Password))
                {
                    var jobseeker = _jobseekerService.GetUserByEmail(model.Email);
                    // Sign In New User
                    _authenticationService.SignIn(jobseeker, model.RememberMe);
                    return RedirectToAction("index", "home");
                }
                else
                {
                    ModelState.AddModelError("loginError", "用户名或密码错误");
                }
            }
            return View(model);
        }
        #endregion

        #endregion

    }
}
